#!/usr/bin/env bash
echo " /**                                             "
echo " | **                                            "
echo " | **  /******  /******/****   /******  /******* "
echo " | ** /**__  **| **_  **_  ** /**__  **| **__  **"
echo " | **| ********| ** \ ** \ **| **  \ **| **  \ **"
echo " | **| **_____/| ** | ** | **| **  | **| **  | **"
echo " | **|  *******| ** | ** | **|  ******/| **  | **"
echo " |__/ \_______/|__/ |__/ |__/ \______/ |__/  |__/"

#function defined
gracefulShutdown(){
  PID=$1
  PORT=$(ss -anp 2>/dev/null|grep -w "${PID}" |grep -w "LISTEN" |awk '{print $5}'|awk -F ":" '{print $NF}')
  curl -X POST http://127.0.0.1:${PORT}/actuator/shutdown
  echo
  echo "The server [${PID}] will be graceful shutdown"
  for wi in {1..50}
  do
    echo -n "."
    num=`ps -p "${PID}" | grep "${PID}" | wc -l`
    if [ ${num} -ge 1 ]; then
      sleep 1s
    else
      break
    fi
  done
  echo
}

forceShutdown(){
  kill -9 $1
  for wi in {1..5}
  do
    echo -n "."
    sleep 1s
  done
  echo
}
eglShutdown(){
  EXIST_PID=$1
  gracefulShutdown ${EXIST_PID}
  num=`ps -p "${EXIST_PID}" | grep "${EXIST_PID}" | wc -l`
  if [ ${num} -ge 1 ]; then
    echo "The server [${EXIST_PID}] has not stoped yet, force shutdown it."
    forceShutdown ${EXIST_PID}
  else
    echo "The server [${EXIST_PID}] has stoped."
  fi
}

APPID=$(echo $EGL_HOME/bms |awk -F "/" '{print $NF}')
# Set PID file
PID_FILE="${EGL_HOME}/bms/${APPID}.pid"

# Check if server is running
if [ -f "${PID_FILE}" ]; then
  EXIST_PID=`cat "${PID_FILE}"`
  num=`ps -p "${EXIST_PID}" | grep "${EXIST_PID}" | wc -l`
  if [ ${num} -ge 1 ]; then
    #echo "Can't start Micro Server server, an existing server[${EXIST_PID}] is running."
    #exit 1
    echo "An existing server[${EXIST_PID}] is running, starting to shutdown it, please wait for a monent."
    eglShutdown ${EXIST_PID}
  fi
  else
    echo "The server [${EXIST_PID}] doesn't running."
fi
